package com.limeng.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

public class ServerThread implements Runnable {

    private Socket socket;

    private Map<String,Servlet> servletMapping;

    public ServerThread(Socket socket, Map<String,Servlet> servletMapping) {
        this.socket = socket;
        this.servletMapping = servletMapping;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            String url = request.getUrl();
            OutputStream outputStream = socket.getOutputStream();
            Response response = new Response(outputStream);
            if(servletMapping.containsKey(url)){
                Servlet servlet = servletMapping.get(url);
                servlet.service(request, response);
            }else{
                response.writeHtml(request.getUrl());
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
